import CryptoJS from 'crypto-js'

const install = (Vue, vm) => {

	Vue.prototype.$sign = {

		// 数据传输签名算法
		buildHeaderSign(url, userStore, requestData, method) {
			let headers = {
				'Content-Type': 'application/json; charset=utf-8', // 强制声明编码
			}
			if (url.includes('/App_Upload/')) {
				headers = {}
			}
			if (userStore && Number(userStore.id) > 0) {
				// 密钥解密
				const app_key = vm.$secret.decryptAES(userStore.app_key);
				const app_secret = vm.$secret.decryptAES(userStore.app_secret);
				const access_token = vm.$secret.decryptAES(userStore.access_token);

				headers.app_key = app_key
				headers.access_token = access_token
				headers.method = url
				headers.timestamp = Date.now()
				headers.version = '1.0'
				// 排序顺序将是：数字、大写字母、下划线、小写字母
				let param_json = {}
				const sortedKeys = Object.keys(requestData).sort()
				sortedKeys.forEach((key) => {
					if (requestData[key] != undefined && requestData[key] != null) {
						if (typeof requestData[key] === 'object' || Array.isArray(requestData[key])) {
							param_json[key] = requestData[key]
						} else {
							//post保持数据类型，get需要转成字符串.toString()
							if (method.toUpperCase() === 'POST') {
								param_json[key] = requestData[key]
							} else {
								param_json[key] = requestData[key].toString()
							}
						}
					}
				})
				// 生成签名（强制 UTF-8 编码，MD5加密结果默认小写）
				const param_json_str = param_json && param_json != '' && Object.keys(param_json).length > 0 ?
					JSON.stringify(param_json) : '';
				// console.log(`${url}消息体参数：`, JSON.stringify(requestData));
				// console.log(`${url}签名串参数：`, param_json_str);
				const paramPattern = app_secret + app_key + headers.method + param_json_str + headers
					.timestamp + headers.version + app_secret;
				// console.log(`${url}生成签名串：`, paramPattern);
				// headers.sign = CryptoJS.MD5(paramPattern).toString();
				headers.sign = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(paramPattern)).toString();
			}
			return headers
		}

	}
}

export default {
	install
}